package com.lt.schoolchat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.schoolchat.annotation.AuthCheck;
import com.lt.schoolchat.common.BaseResponse;
import com.lt.schoolchat.common.DeleteRequest;
import com.lt.schoolchat.common.ErrorCode;
import com.lt.schoolchat.common.ResultUtils;
import com.lt.schoolchat.constant.CommonConstant;
import com.lt.schoolchat.exception.BusinessException;
import com.lt.schoolchat.model.dto.log.SysLogAddRequest;
import com.lt.schoolchat.model.dto.log.SysLogQueryRequest;
import com.lt.schoolchat.model.dto.log.SysLogUpdateRequest;
import com.lt.schoolchat.model.entity.SysLog;
import com.lt.schoolchat.service.SysLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import sun.net.util.IPAddressUtil;

import javax.annotation.Resource;

/**
 * @description:
 * @author: ~Teng~
 * @date: 2023/6/10 10:56
 */
@RestController
@RequestMapping("/log")
@Api(tags = "系统日志接口")
public class LogController {
    @Resource
    private SysLogService sysLogService;

    @PostMapping("/add")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("创建日志")
    public BaseResponse<Long> addReport(@RequestBody SysLogAddRequest sysLogAddRequest) {
        if (sysLogAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String requestIp = sysLogAddRequest.getRequestIp();
        // 校验数据
        boolean isValid = IPAddressUtil.isIPv4LiteralAddress(requestIp);
        if (!isValid) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法IPV4地址");
        }
        SysLog sysLog = new SysLog();
        BeanUtils.copyProperties(sysLogAddRequest, sysLog);
        boolean result = sysLogService.save(sysLog);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long logId = sysLog.getId();
        return ResultUtils.success(logId);
    }

    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("删除日志")
    public BaseResponse<Boolean> deleteReport(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        SysLog sysLog = sysLogService.getById(id);
        if (sysLog == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = sysLogService.removeById(id);
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("更新日志")
    public BaseResponse<Boolean> updateReport(@RequestBody SysLogUpdateRequest sysLogUpdateRequest) {
        if (sysLogUpdateRequest == null || sysLogUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String requestIp = sysLogUpdateRequest.getRequestIp();
        boolean isValid = IPAddressUtil.isIPv4LiteralAddress(requestIp);
        if (!isValid) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法IPV4地址");
        }
        SysLog sysLog = new SysLog();
        BeanUtils.copyProperties(sysLogUpdateRequest, sysLog);
        long id = sysLogUpdateRequest.getId();
        // 判断是否存在
        SysLog oldSysLog = sysLogService.getById(id);
        if (oldSysLog == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = sysLogService.updateById(sysLog);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(result);
    }

    @GetMapping("/get")
    @ApiOperation("根据id获取日志")
    public BaseResponse<SysLog> getReportById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysLog sysLog = sysLogService.getById(id);
        return ResultUtils.success(sysLog);
    }

    @GetMapping("/list/page")
    @ApiOperation("分页获取日志列表")
    public BaseResponse<Page<SysLog>> listReportByPage(SysLogQueryRequest sysLogQueryRequest) {
        if (sysLogQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = sysLogQueryRequest.getCurrent();
        long size = sysLogQueryRequest.getPageSize();
        String sortField = sysLogQueryRequest.getSortField();
        String sortOrder = sysLogQueryRequest.getSortOrder();
        String requestIp = sysLogQueryRequest.getRequestIp();
        Long cost = sysLogQueryRequest.getCost();
        String requestUrl = sysLogQueryRequest.getRequestUrl();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(requestIp), "requestIp", requestIp);
        queryWrapper.eq(StringUtils.isNotBlank(requestUrl), "requestUrl", requestUrl);
        queryWrapper.ge(cost != null, "cost", cost);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<SysLog> sysLogPage = sysLogService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(sysLogPage);
    }
}
